package sivan.algorithm;

public class ArraySort {

    public static void main(String[] args) {
        int[] arr = {3, 1, 2, 5, 4, 6, 9, 7, 10, 8};
//        selectSort(arr);
//        bubblingSort(arr);
        quickSort(arr);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }

    /**
     * 选择排序
     *
     * @param arr
     * @return
     */
    public static int[] selectSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int k = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[k]) {
                    k = j;
                }
            }

            if (k != i) {
                int temp = arr[i];
                arr[i] = arr[k];
                arr[k] = temp;
            }
        }
        return arr;
    }

    /**
     * 冒泡排序
     *
     * @param arr
     * @return
     */
    public static int[] bubblingSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    public static int[] quickSort(int[] arr) {
        if (arr.length > 0) {
            quickSort(arr, 0, arr.length - 1);
        }
        return arr;
    }

    private static void quickSort(int[] arr, int start, int end) {
        if (start > end) {
            return ;
        }
        int low = start;
        int high = end;
        int temp = arr[low];
        while (low < high) {
            while (low < high && arr[high] > temp) {
                high--;
            }
            arr[low] = arr[high];

            while (low < high && arr[low] <= temp) {
                low++;
            }
            arr[high] = arr[low];
        }
        arr[low] = temp;

        quickSort(arr, start, low - 1);
        quickSort(arr, low + 1, end);
    }
}
